﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Bookkeeping.Core.Entities
{
    public enum PostType { Income, Expense, Saving }

    public class Post : IIdentifiable
    {
        IList<Tag> _tags = new List<Tag>();

        public virtual int Id { get; set; }
        public virtual double Amount { get; set; }
        public virtual string Comment { get; set; }
        public virtual string Name { get; set; }
        public virtual PostType Type { get; set; }
        public virtual DateTime DateTime { get; set; }

        public virtual IEnumerable<Tag> Tags
        {
            get
            {
                return _tags;
            }
        }

        public virtual void AddTag(Tag tag)
        {
            _tags.Add(tag);
        }

        public virtual void RemoveTag(int id)
        {
            Tag tagToRemove = _tags.FirstOrDefault(t => t.Id == id);

            if (tagToRemove != null)
                _tags.Remove(tagToRemove);
        }

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }

            Post other = (Post)obj;

            if (!AreTagsEqual(other))
                return false;

            return Id == other.Id &&
                Name == other.Name &&
                Comment == other.Comment &&
                Amount == other.Amount &&
                Type == other.Type;
        }

        private bool AreTagsEqual(Post other)
        {
            if (this._tags.Count != other._tags.Count)
                return false;

            for (int i = 0; i < _tags.Count; i++)
            {
                if (!this._tags[i].Equals(other._tags[i]))
                    return false;
            }

            return true;
        }

        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }

        public override string ToString()
        {
            return string.Format("Id: {0}, Type: {1}, Name: {2}, Amount: {3}", Id, Type, Name, Amount);
        }
    }
}
